<?php
namespace app\api\controller\wap;

use app\command\HistoryTrade;
use app\command\RuleCalculation;
use app\command\TradeServer;
use app\common\model\system\SqlToRedis;
use app\common\model\users\UsersKey;
use mall\library\Huobi;
use think\facade\Cache;
use think\facade\Db;
use think\facade\Request;

class Swoole extends Base{

    private $scale = 30;

    /**
     * 获取等待进程数量
     * @return mixed
     * @throws \think\Exception
     */
    private function getWaitProcess($port) {
        return HistoryTrade::tcpTableQuery(\app\command\Swoole::TABLE_PROCESS_WAIT,$port);
    }

    /**
     * 获取表记录统计
     * @return mixed
     * @throws \think\Exception
     */
    private function getTableCount($port) {
        $result = HistoryTrade::tcpTableQuery(\app\command\Swoole::TABLE_SAVE_COUNT,$port);
        $list = $result['result'];
        array_multisort($list,SORT_DESC,array_column($list,'last_count'));
        $result['result'] = $list;
        return $result;
    }

    /**
     * 获取单次请求火币需要的时间
     */
    private function checkApiTime() {
        $times = 10;
        $huobi = new Huobi('','','');
        $timesList = [
            'unitTime'  => 0,
            'times'     => 0,
            'countTime' => 0,
            'list'      => [],
        ];
        for($i=0;$i<$times;++$i) {
            $tmp = [
                microtime(true)
            ];
            //$result = $huobi->get_market_tickers();
            $result = $huobi->get_detail_merged('xlmusdt');
            print_r($result);
            $tmp[] = microtime(true);
            $tmp[] = $tmp[1] - $tmp[0];
            $tmp[] = (strlen(json_encode($result))/1024) . ' KB';
            $timesList['times']++;
            $timesList['list'][] = $tmp;
            $timesList['countTime'] = bcadd($timesList['countTime'],$tmp[2],4);
        }
        $timesList['unitTime'] = bcdiv($timesList['countTime'],$timesList['times'],4);
        return $timesList;

    }

    /**
     * 获取试试输入列表（未读取）
     * @throws \think\Exception
     */
    private function getInputList($port) {
        $result = HistoryTrade::tcpTableQuery(HistoryTrade::TABLE_INPUT_PRICE,$port);
      //  $result = HistoryTrade::tcpTableQuery(HistoryTrade::TABLE_INPUT_PRICE . ' market_xlmusdt price');

        return $result;
    }

    /**
     * 设置火币价格
     * @param $symbol
     * @param $price
     */
    private function setInput($symbol,$price,$port = null) {
        HistoryTrade::tcpTableQuery(implode(' ',['setInput',$symbol,$price]),$port);
    }

    /**
     * 获取消耗记录表
     */
    private function getTakeTime($port) {
        return HistoryTrade::tcpTableQuery(HistoryTrade::TABLE_TAKE_TIME,$port);
    }


    private function getPidList() {
        $dir = dirname(dirname(dirname(dirname(__FILE__)))) . '/command/pid/';
        $logFile = $dir . 'count.log';
        $message = explode("\n",trim(file_get_contents($logFile)));

        $nameFile = $dir . 'name.log';
        $nameList = explode("\n",trim(file_get_contents($nameFile)));
        $pidNameList = [

        ];
        foreach($nameList as $value) {
            $tmp = explode(' ',$value);
            $pidNameList[$tmp[0]] = $tmp[1];
        }

        $pidList = [];
        foreach($message as $value) {
            $value = explode(' ',$value);
            $id = $value[3];
            $pid = $value[4];

            $data = [

            ];
            if(array_key_exists($id,$pidNameList)) {
                $data['name'] = $pidNameList[$id];
            }
            switch ($value[2]) {
                case 'start':
                    $data['start'] = $value[0] . ' ' . $value[1];
                    break;
                case 'close':
                    $data['close'] = $value[0] . ' ' . $value[1];
                    break;
            }

            if(!array_key_exists($pid,$pidList)) {
                $pidList[$id] = array_merge([
                    'name'  => '',
                    'start' => '',
                    'close'   => '',
                    'subList'   => [],
                ],$data);
            } else {
                $pidList[$pid]['subList'][$id] = array_merge(
                    array_key_exists($id,$pidList[$pid]['subList'])?$pidList[$pid]['subList'][$id]:[
                        'name'  => '',
                        'start' => '',
                        'close'   => '',
                    ],$data);
            }

        }
        echo '<pre>';
        echo count($pidList);
        print_r($pidList);
        exit;
    }

    private function testSSL() {
        $sock = fsockopen('wss://api.huobi.pro/feed',443 , $errno, $errstr, 2);
        var_dump($sock);
    }

    private function apiRunHistory($port) {
        return HistoryTrade::tcpTableQuery(RuleCalculation::TABLE_LAST_REQUEST . ' ' . request()->get('id'),$port);
    }

    private function getSelectList($port) {
        return HistoryTrade::tcpTableQuery(HistoryTrade::TABLE_SELECT_LIST,$port);
    }


    /**
     * 统计日志
     */
    private function countLog() {
        $file = request()->get('file');
        $file = dirname(dirname(dirname(dirname(__FILE__)))) . '/command/takeTime/' . ($file?$file:'run') . '.log';
        if(!file_exists($file)) {
            die('not find File');
        }
        $content = trim(file_get_contents($file));
        $content = explode("\n",$content);
        $contentList = array_map(function($value){
            return json_decode(trim($value),true);
        },$content);
        $countList = [];
        $readErrLog = [];
        foreach($contentList as $value) {
            $type = $value['type'];
            if(!array_key_exists($type,$countList)) {
                $countList[$type] = [];
            }
            $key = $value['symbol'] . '_' . $value['ts'] . '_' . $value['trade-id'];
            switch($type) {
                case 7:
                case 6:
                    if(array_key_exists($key,$countList[$type])) {
                        $countList[$type][$key] = [];
                    }
                    $countList[$type][$key][$value['rule_id']] = $value;
                    break;
                case 21:
                    $historyTime = explode('.',$value['time']);
                    $historyTime = date('Y-m-d H:i:s',$historyTime[0]) . ' ' . sprintf('%-4d',array_key_exists(1,$historyTime)?$historyTime[1]:0);
                    $value = [$historyTime,sprintf('%-6d',$value['pid']),$value['symbol']];
                    $readErrLog[] = implode(' ',$value);
                    break;
                default:
                    $countList[$type][$key] = $value;
            }
        }

        $startTime = $endTime = 0;
        $historyList = [];
        foreach($countList[3] as $key=>$value) {
            if($startTime == 0 || $startTime > $value['time']) {
                $startTime = $value['time'];
            }
            if($endTime == 0 || $endTime < $value['time']) {
                $endTime = $value['time'];
            }

            $historyTime = explode('.',$value['time']);
            $historyTime = date('Y-m-d H:i:s',$historyTime[0]) . ' ' . sprintf('%4d',array_key_exists(1,$historyTime)?$historyTime[1]:0);
            $distribution = array_key_exists($key,$countList[4])?bcsub($countList[4][$key]['time'],$value['time'],4):null;
            $calculationBefor = array_key_exists($key,$countList[5])?bcsub($countList[5][$key]['time'],$value['time'],4):null;
            if(array_key_exists($key,$countList[6])) {
                $calculation = bcsub(bcdiv(array_sum(array_column($countList[6][$key],'time')),count($countList[6][$key]),4),$value['time'],4);
            } else {
                $calculation = null;
            }
            if(array_key_exists(7,$countList) && array_key_exists($key,$countList[7])) {
                $apply = bcsub(bcdiv(array_sum(array_column($countList[7][$key],'time')),count($countList[7][$key]),4),$value['time'],4);
            } else {
                $apply = null;
            }
            $historyList[$key] = [$historyTime,$distribution,$calculationBefor,$calculation,$apply];
        }

        $timeCount = [];
        $errorList = [];
        foreach($historyList as $key=>$value) {
            if(is_null($value[3])) {
                $errorList[$key] = $value;
                continue;
            }
            $timeCount[] = $value[3];
        }
        $countTime = bcsub($endTime,$startTime,4);
        $countSum = array_sum($timeCount);
        $countNum =  count($timeCount);
        $maxTime = $minTime = 0;
        foreach($timeCount as $time) {
            if($maxTime == 0 || bccomp($maxTime,$time,4) == -1) {
                $maxTime = $time;
            }

            if($minTime == 0 || (bccomp($minTime,$time,4) == 1 && $time > 0)) {
                $minTime = $time;
            }
        }
        echo '总记录数：' . $countNum . "\n\n";
        echo '总耗时：' . $countTime . ' ；每秒获取记录数：' . bcdiv($countNum,$countTime,0) . "\n\n";
        echo '每条行情到计算结束平均耗时：' . bcdiv($countSum,$countNum,4) . "；最长耗时：" . $maxTime . '；用时耗时：' . $minTime . "\n\n";

        echo "不完整记录：\n";
        print_r($errorList);

        echo "\n";
        echo  "错误记录：\n";
        foreach($readErrLog as $key=>$value) {
            echo sprintf('%5d',$key) . ' => ' . $value . "\n";
        }
    }


    public function convert_scientific_number_to_normal($number)
    {
        if(stripos($number, 'e') === false) {
            //判断是否为科学计数法
            return $number;
        }

        if(!preg_match(
            "/^([\\d.]+)[eE]([\\d\\-\\+]+)$/",
            str_replace(array(" ", ","), "", trim($number)), $matches)
        ) {
            //提取科学计数法中有效的数据，无法处理则直接返回
            return $number;
        }

        //对数字前后的0和点进行处理，防止数据干扰，实际上正确的科学计数法没有这个问题
        $data = preg_replace(array("/^[0]+/"), "", rtrim($matches[1], "0."));
        $length = (int)$matches[2];
        if($data[0] == ".") {
            //由于最前面的0可能被替换掉了，这里是小数要将0补齐
            $data = "0{$data}";
        }

        //这里有一种特殊可能，无需处理
        if($length == 0) {
            return $data;
        }

        //记住当前小数点的位置，用于判断左右移动
        $dot_position = strpos($data, ".");
        if($dot_position === false) {
            $dot_position = strlen($data);
        }

        //正式数据处理中，是不需要点号的，最后输出时会添加上去
        $data = str_replace(".", "", $data);


        if($length > 0) {
            //如果科学计数长度大于0

            //获取要添加0的个数，并在数据后面补充
            $repeat_length = $length - (strlen($data) - $dot_position);
            if($repeat_length > 0) {
                $data .= str_repeat('0', $repeat_length);
            }

            //小数点向后移n位
            $dot_position += $length;
            $data = ltrim(substr($data, 0, $dot_position), "0").".".substr($data, $dot_position);

        } elseif($length < 0) {
            //当前是一个负数

            //获取要重复的0的个数
            $repeat_length = abs($length) - $dot_position;
            if($repeat_length > 0) {
                //这里的值可能是小于0的数，由于小数点过长
                $data = str_repeat('0', $repeat_length).$data;
            }

            $dot_position += $length;//此处length为负数，直接操作
            if($dot_position < 1) {
                //补充数据处理，如果当前位置小于0则表示无需处理，直接补小数点即可
                $data = ".{$data}";
            } else {
                $data = substr($data, 0, $dot_position).".".substr($data, $dot_position);
            }
        }
        if($data[0] == ".") {
            //数据补0
            $data = "0{$data}";
        }
        return trim($data, ".");
    }

    // 获取执行中的请求
    private function getCallApi() {
        return HistoryTrade::tcpTableQuery(RuleCalculation::TABLE_LAST_REQUEST . ' ' . request()->get('id'));

    }


    /**
     * 统计账户余额
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    private function countBalance($getFunc) {
        $id = explode(',',trim($getFunc('id')));
        $scale = 30;
        // 计算计算金额
        $getAmountFunc = function($currency,$number) use($scale){
            static $priceList = [];
            if(!array_key_exists($currency,$priceList)) {
                // 获取实时价格
                $code = $currency . 'usdt';
                $time = microtime(true);
                $price = (new Huobi('','',''))->get_history_trade($code,1)['data'][0]['data'][0]['price'];
                echo '获取当前价格【' . $code . '】：' . (microtime(true) - $time) . "\n";
                $priceList[$currency] = $price;
            }

            return bcmul($number,$priceList[$currency],$scale);

        };
        $idList = array_map(function($id){
            return intval($id);
        },$id);
        $result = [];
        $time = microtime(true);
        (new UsersKey())->alias('key')->where(['key.id'=>$idList])->field(['key.id'])->select();
        echo '查询时间：' . (microtime(true) - $time) . "\n";
        $time = microtime(true);
    //    file_get_contents('http://3.112.247.33:13902');
        echo '打开文件时间：' . (microtime(true) - $time) . "\n";

        $time = microtime(true);
        if($userList = (new UsersKey())->alias('key')
            ->join('users user','user.id=key.id','INNER')
            ->where(['key.id'=>$idList])->field(['key.id','user.username','key.account_id','key.access_key','key.secret_key'])->select()) {
            echo '查询时间：' . (microtime(true) - $time) . "\n";
            foreach($userList as $key=>$value) {
                $value = $value->getData();
                $time = microtime(true);
                $balanceList = (new Huobi($value['account_id'],$value['access_key'],$value['secret_key']))->get_balance($value['account_id']);
                echo '获取余额【' . $value['account_id'] . '】：' . (microtime(true) - $time) . "\n";
                if(!array_key_exists($value['id'],$result)) {
                    $result[$value['id']] = [
                        'username'  => 0,
                        'balance'   => 0,
                        'currencyBalance'   => 0,
                    ];
                }
                $dataList = [];
                foreach($balanceList['data']['list'] as $balance) {
                    if(bccomp($balance['balance'],0,$scale) != 0) {
                        $dataList[] = $balance;
                        if($balance['currency'] == 'usdt') {
                            $result[$value['id']]['balance'] = bcadd($result[$value['id']]['balance'],$balance['balance'],$scale);
                        } else {
                            echo $balance['currency'] . ' ';
                            echo $getAmountFunc($balance['currency'],$balance['balance']);
                            echo '(' . $balance['balance'] . ')';
                            echo "<br />";
                            $result[$value['id']]['currencyBalance'] = bcadd($result[$value['id']]['currencyBalance'],$getAmountFunc($balance['currency'],$balance['balance']),$scale);
                        }
                    }
                }
                $result[$value['id']]['totalAmount'] = bcadd($result[$value['id']]['balance'],$result[$value['id']]['currencyBalance'],$scale);
                foreach($result[$value['id']] as &$tmp) {
                    $tmp = rtrim(rtrim($tmp,0),'.');
                }
                $result[$value['id']]['username'] = $value['username'];
           //     $result[$value['id']]['dataList'] = $dataList;
            }
        }

        echo '<pre>';
        print_r($result);

    }


    /**
     * 按系统数量计算用户金额
     */
    private function countBalanceSystem($getFunc) {
        $id = explode(',',trim($getFunc('id')));
        $scale = 30;
        // 计算计算金额
        $getAmountFunc = function($currency,$number) use($scale){
            static $priceList = [];
            if(!array_key_exists($currency,$priceList)) {
                // 获取实时价格
                $code = $currency . 'usdt';
                $price = (new Huobi('','',''))->get_history_trade($code,1)['data'][0]['data'][0]['price'];
                $priceList[$currency] = $price;
            }

            return bcmul($number,$priceList[$currency],$scale);

        };
        $idList = array_map(function($id){
            return intval($id);
        },$id);
        $result = [];

        $tmp =Db::query('SELECT user_id,coin_id,coin_name,sum(if(type=1,field_quantity-field_fees,0-field_quantity)) as quantity from b_coin_rule_run_trade WHERE user_id in(' . implode(',',$idList) . ') GROUP BY user_id,coin_id');
        $coinList = [];
        foreach($tmp  as $t) {
            if(!array_key_exists($t['user_id'],$coinList)) {
                $coinList[$t['user_id']] = [];
            }
            $coinList[$t['user_id']][] = $t;
        }
        if($userList = (new UsersKey())->alias('key')
            ->join('users user','user.id=key.id','INNER')
            ->where(['key.id'=>$idList])->field(['key.id','user.username','key.account_id','key.access_key','key.secret_key'])->select()) {

            foreach ($userList as $key => $value) {
                $value = $value->getData();
                $balanceList = (new Huobi($value['account_id'], $value['access_key'], $value['secret_key']))->get_balance($value['account_id']);
                if (!array_key_exists($value['id'], $result)) {
                    $result[$value['id']] = [
                        'username' => 0,
                        'balance' => 0,
                        'currencyBalance' => 0,
                    ];
                }
                $dataList = [];
                foreach ($balanceList['data']['list'] as $balance) {
                    if (bccomp($balance['balance'], 0, $scale) != 0) {
                        $dataList[] = $balance;
                        if ($balance['currency'] == 'usdt') {
                            $result[$value['id']]['balance'] = bcadd($result[$value['id']]['balance'], $balance['balance'], $scale);
                        }
                    }
                }
                if(array_key_exists($value['id'],$coinList)) {
                    foreach($coinList[$value['id']] as $balance) {
                        $result[$value['id']]['currencyBalance'] = bcadd($result[$value['id']]['currencyBalance'], $getAmountFunc(strtolower($balance['coin_name']), $balance['quantity']), $scale);
                    }
                }
                $result[$value['id']]['totalAmount'] = bcadd($result[$value['id']]['balance'], $result[$value['id']]['currencyBalance'], $scale);
                foreach ($result[$value['id']] as &$tmp) {
                    $tmp = rtrim(rtrim($tmp, 0), '.');
                }
                $result[$value['id']]['username'] = $value['username'];
                //     $result[$value['id']]['dataList'] = $dataList;
            }
        }
        print_r($result);
        print_r($coinList);
    }

    public function countRule() {
        set_time_limit(180);
        $list = (new \app\common\model\coin\CoinRule())->alias('rule')
            ->join('coin','coin.id=rule.coin_id','INNER')
            ->join('coin_rule_run run','rule.coin_rule_run_id=run.id','INNER')
            ->join('users user','user.id=rule.user_id','INNER')
            ->join('users_key key','key.id=rule.user_id','INNER')
            ->field([
                'coin.code',
                'coin.sell_price_scale',
                'rule.user_id',
                'user.username',
                'run.amount',
                'run.quantity',
                'run.unit_price',
                'key.account_id',
                'key.access_key',
                'key.secret_key',
            ])
            ->order(['rule.user_id'=>'DESC'])
            ->select()->toArray();
        $userBalanceList = [];
        $saveList = [];
        $frozenList = [];
        $errorList = [];
        $apiErrorList = [];
        foreach($list as $details) {
            $userId = $details['user_id'];
            if(!array_key_exists($userId,$userBalanceList)) {
                $userBalanceList[$userId] = [];
                $balance = (new Huobi($details['account_id'],$details['access_key'],$details['secret_key']))->get_balance($details['account_id']);
                if($balance['status'] == 'ok') {
                    $balance = $balance['data']['list'];
                } else {
                    $balance = [];
                    $apiErrorList[$userId] = $details['username'];
                }
                foreach($balance as $balanceDetails) {
                    if(bccomp($balanceDetails['balance'],0,6) == 1) {
                        $code = $balanceDetails['currency'] . 'usdt';
                        if(!array_key_exists($code,$userBalanceList[$userId])) {
                            $userBalanceList[$userId][$code] = [
                                'trade'     => 0,
                                'frozen'    => 0,
                            ];
                        }
                        $userBalanceList[$userId][$code][$balanceDetails['type']] = $balanceDetails['balance'];
                    }
                }
            }
            if(!array_key_exists($details['code'],$userBalanceList[$userId])) {
                continue;
            }
            $details = array_merge($details,$userBalanceList[$userId][$details['code']]);
            if(bccomp($details['quantity'],0,20) != 1) {
                $errorList[] = $details;
                continue;
            }
            $details['rate'] = bcmul(bcdiv($details['trade'],$details['quantity'],20),100,2);

            if(bccomp($details['rate'],50,2) == 1) {
                $saveList[] = $details;
            }

            if(bccomp($details['frozen'],0,6) == 1) {
                $frozenList[] = $details;
            }
        }

        $result = [];
        echo '<table>';
        echo '<tr>';
        echo '<td>用户ID</td>';
        echo '<td>用户名</td>';
        echo '<td>币种</td>';
        echo '<td>成本金额</td>';
        echo '<td>成本数</td>';
        echo '<td>账号金额</td>';
        echo '<td>账号数量</td>';
        echo '<td>占比</td>';
        echo '</tr>';
        foreach($saveList as $details) {
            echo '<tr>';
            echo '<td>' . $details['user_id'] . '</td>';
            echo '<td>' . $details['username'] . '</td>';
            echo '<td>' . substr($details['code'],0,-4) . '</td>';
            echo '<td>' . round($details['amount']) . '</td>';
            echo '<td>' . $details['quantity'] . '</td>';
            echo '<td>' . round(bcmul($details['trade'],$details['unit_price'],20)) . '</td>';
            echo '<td>' . $details['trade'] . '</td>';
            echo '<td>' . $details['rate'] . '</td>';
            echo '</tr>';
        }
        echo '</table>';

        echo '<pre>';
        print_r($result);
        print_r($apiErrorList);
        exit;

        echo count($saveList),'<br />';
        echo count($frozenList),'<br />';
        echo count($errorList),'<br />';

        exit;
    }

    public function test(\swoole_http_request $request = null){
        if(empty($request) || $request->fd == 0) {
            $request = new \swoole_http_request();
            $request->server = request()->server();
            $request->get = request()->get();
        }
        // 获取get参数
        $getFunc = function($key) use($request) {
            return array_key_exists($key,$request->get)?$request->get[$key]:'';
        };
       // $request = new \swoole_http_request();
        $port = $getFunc('port');
        echo '<pre>';
        switch($getFunc('t')) {
            case 'wait':
                print_r($this->getWaitProcess($port,$getFunc));
                exit;
            case 'api_check':
                print_r($this->checkApiTime($port,$getFunc));
                exit;
            case 'get_input':   //获取当前价格
                print_r($this->getInputList($port,$getFunc));
                exit;
            case 'set_input':   // 输入价格
                $this->setInput($getFunc('symbol'),$getFunc('price'));
                exit;
            case 'count':
                print_r($this->getTableCount($port,$getFunc));
                exit;
            case 'take_time':
                print_r($this->getTakeTime($port,$getFunc));
                exit;
            case 'get_pid':
                print_r($this->getPidList($port,$getFunc));
                exit;
            case 'test':
                print_r($this->testSSL($port,$getFunc));
                exit;
            case 'history':
                $result = HistoryTrade::tcpTableQuery(HistoryTrade::TABLE_SELECT_RUN,$port);
                $list = $result['result'];
                array_multisort($list,SORT_DESC,array_column($list,'lastTime'));

                $result = [];
                foreach($list as $symbol=>$value) {
                    $result[$symbol] = date('Y-m-d H:i:s',$value['lastTime']);
                }
                arsort($result);
                print_r($result);
                exit;
             case 'api_run':
                 print_r($this->apiRunHistory($port));
                exit;

            case 'select_list':
                print_r($this->getSelectList($port));
                exit;
            case 'userRuleRefresh': // 刷新用户规则
                (new SqlToRedis())->getUserRule(1,true);
                exit;
            case 'balance': //统计余额
                $this->countBalance($getFunc);
                exit;
            case 'balanceSystem': //统计余额
                $this->countBalanceSystem($getFunc);
                exit;
            case 'trade':   //测试交易
                exit;
                ini_set('max_execution_time', 180);
                $symbolList = [
                    /*'sushiusdt',*/'linkusdt','filusdt','nearusdt','ethusdt','aaveusdt','htusdt','ltcusdt','zrxusdt','btcusdt',
                    'adausdt','xrpusdt','kncusdt','eosusdt','avaxusdt','mkrusdt','1inchusdt','bchusdt','dotusdt','ksmusdt','omgusdt','uniusdt',
                    'atomusdt','trxusdt','solusdt','crvusdt','xlmusdt','compusdt','enjusdt'
                ];
                $symbol = 'sushiusdt';
                $accountId = '23150905';
                $huobi = new Huobi($accountId,'9bc53367-mn8ikls4qg-58abf940-2a719','7f54d9ca-4064fa0f-4f1ba2f7-72eac');
               /* echo 'sushiusdt,265895369725468|';
                foreach($symbolList as $symbol) {
                    try {
                        if(($result = $huobi->place_order($accountId,10,0,$symbol,'buy-market')) && $result['status'] == 'ok') {
                            echo implode(',',[$symbol,$result['data']]) . '|';
                        }
                    }catch (\Exception $e) {

                    }
                }*/

                // 小数点位数限制
                $priceScaleList = 'sushiusdt , 265895369725468 , 0.001 , 13.8657 , 13.86107810 , error , priceScale , 4|linkusdt , 265895545771070 , 0.001 , 36.242 , 36.22991934 , error , priceScale , 4|filusdt , 265895520310546 , 0.001 , 149.8784 , 149.82844054 , error , priceScale , 4|nearusdt , 265895554521634 , 0.001 , 5.0634 , 5.06171220 , error , priceScale , 4|ethusdt , 265895520311719 , 0.001 , 2708.3 , 2707.39723334 , error , priceScale , 2|aaveusdt , 265895545837974 , 0.001 , 470.5566 , 470.39974780 , error , priceScale , 4|htusdt , 265895563076630 , 0.001 , 18.3175 , 18.31139417 , error , priceScale , 4|ltcusdt , 265895494918289 , 0.001 , 256.58 , 256.49447334 , error , priceScale , 2|zrxusdt , 265895503331945 , 0.001 , 1.7049 , 1.70433170 , error , priceScale , 4|btcusdt , 265895562936355 , 0.001 , 54811.6 , 54793.32946667 , error , priceScale , 2|adausdt , 265895528661476 , 0.001 , 1.297236 , 1.29680359 , error , priceScale , 6|xrpusdt , 265895562871075 , 0.001 , 1.35569 , 1.35523811 , error , priceScale , 5|kncusdt , 265898138608810 , 0.001 , 3.0123 , 3.01129590 , error , priceScale , 4|eosusdt , 265898138609225 , 0.001 , 5.9412 , 5.93921960 , error , priceScale , 4|avaxusdt , 265895672316162 , 0.001 , 27.4513 , 27.44214957 , error , priceScale , 4|mkrusdt , 265895511822999 , 0.001 , 4361.08 , 4359.62630667 , error , priceScale , 2|1inchusdt , 265895554321367 , 0.001 , 4.880171 , 4.87854428 , error , priceScale , 6|bchusdt , 265895571525228 , 0.001 , 883.7 , 883.40543334 , error , priceScale , 2|dotusdt , 265895571427787 , 0.001 , 33.6703 , 33.65907657 , error , priceScale , 4|ksmusdt , 265895554224163 , 0.001 , 395.7996 , 395.66766680 , error , priceScale , 4|omgusdt , 265895537187233 , 0.001 , 7.374 , 7.37154200 , error , priceScale , 4|uniusdt , 265895503339102 , 0.001 , 42.2613 , 42.24721290 , error , priceScale , 4|atomusdt , 265895562910662 , 0.001 , 22.8073 , 22.79969757 , error , priceScale , 4|trxusdt , 265895562911326 , 0.001 , 0.12231 , 0.12226923 , error , priceScale , 6|solusdt , 265895571496737 , 0.001 , 46.3366 , 46.32115447 , error , priceScale , 4|crvusdt , 265895537190153 , 0.001 , 2.9798 , 2.97880674 , error , priceScale , 4|xlmusdt , 265895562912991 , 0.001 , 0.493893 , 0.49372837 , error , priceScale , 6|compusdt , 265895562815067 , 0.001 , 653.01 , 652.79233000 , error , priceScale , 2|enjusdt , 265895520175548 , 0.001 , 2.6989 , 2.69800037 , error , priceScale , 4';
                // 最小数量
                $minNumberList  = 'sushiusdt , 265895369725468 , 0.0001 , 13.9526 , 13.94794914 , error , minNumber , 0.001|linkusdt , 265895545771070 , 0.0001 , 36.1371 , 36.12505430 , error , minNumber , 0.01|filusdt , 265895520310546 , 0.0001 , 150.0292 , 149.97919027 , error , minNumber , 0|nearusdt , 265895554521634 , 0.0001 , 5.0099 , 5.00823004 , error , minNumber , 0.01|ethusdt , 265895520311719 , 0.0001 , 2716.6 , 2715.69446667 , error , minNumber , 0.001|aaveusdt , 265895545837974 , 0.0001 , 475.4096 , 475.25113014 , error , minNumber , 0|htusdt , 265895563076630 , 0.0001 , 18.3631 , 18.35697897 , error , minNumber , 0.1|ltcusdt , 265895494918289 , 0.0001 , 255.54 , 255.45482000 , error , minNumber , 0.001|zrxusdt , 265895503331945 , 0.0001 , 1.6867 , 1.68613777 , error , minNumber , 0.1|btcusdt , 265895562936355 , 0.0001 , 54708.1 , 54689.86396667 , error , amountScale , 6|adausdt , 265895528661476 , 0.0001 , 1.301732 , 1.30129809 , error , minNumber , 0.1|xrpusdt , 265895562871075 , 0.0001 , 1.36218 , 1.36172594 , error , minNumber , 1|kncusdt , 265898138608810 , 0.0001 , 3.0331 , 3.03208897 , error , minNumber , 0.01|eosusdt , 265898138609225 , 0.0001 , 5.8981 , 5.89613397 , error , minNumber , 0.1|avaxusdt , 265895672316162 , 0.0001 , 27.5933 , 27.58410224 , error , minNumber , 0.001|mkrusdt , 265895511822999 , 0.0001 , 4376.82 , 4375.36106000 , error , minNumber  ,  0.0001|1inchusdt , 265895554321367 , 0.0001 , 4.894109 , 4.89247764 , error , minNumber , 0.1|bchusdt , 265895571525228 , 0.0001 , 881.61 , 881.31613000 , error , minNumber , 0.001|dotusdt , 265895571427787 , 0.0001 , 33.6028 , 33.59159907 , error , minNumber , 0.01|ksmusdt , 265895554224163 , 0.0001 , 402.0168 , 401.88279440 , error , minNumber , 0.01|omgusdt , 265895537187233 , 0.0001 , 7.3573 , 7.35484757 , error , minNumber , 0.01|uniusdt , 265895503339102 , 0.0001 , 42.0748 , 42.06077507 , error , minNumber , 0.01|atomusdt , 265895562910662 , 0.0001 , 22.5243 , 22.51679190 , error , minNumber , 0.01|trxusdt , 265895562911326 , 0.0001 , 0.121748 , 0.12170742 , error , minNumber , 1|solusdt , 265895571496737 , 0.0001 , 45.96 , 45.94468000 , error , minNumber , 0.01|crvusdt , 265895537190153 , 0.0001 , 2.9822 , 2.98120594 , error , minNumber , 0.01|xlmusdt , 265895562912991 , 0.0001 , 0.49262 , 0.49245580 , error , minNumber , 0.1|compusdt , 265895562815067 , 0.0001 , 656.35 , 656.13121667 , error , minNumber , 0.0001|enjusdt , 265895520175548 , 0.0001 , 2.6693 , 2.66841024 , error , minNumber , 0.001';
                // 数量小数点位数
                $amountScaleList = 'sushiusdt , 265895369725468 , 0.3127819699 , 13.96 , 13.95534667 , error , amountScale , 4|linkusdt , 265895545771070 , 0.1209739640 , 36.3446 , 36.33248514 , error , amountScale , 2|filusdt , 265895520310546 , 0.0289156615 , 150.012 , 149.96199600 , error , amountScale , 4|nearusdt , 265895554521634 , 0.8786866539 , 5.0392 , 5.03752027 , error , amountScale , 2|ethusdt , 265895520311719 , 0.0016195498 , 2714.34 , 2713.43522000 , error , amountScale , 4|aaveusdt , 265895545837974 , 0.0092226989 , 467.6175 , 467.46162750 , error , amountScale , 4|htusdt , 265895563076630 , 0.2370552512 , 18.2669 , 18.26081104 , error , amountScale , 4|ltcusdt , 265895494918289 , 0.0170670643 , 256.94 , 256.85435334 , error , amountScale , 4|zrxusdt , 265895503331945 , 2.5543830192 , 1.7048 , 1.70423174 , error , amountScale , 2|btcusdt , 265895562936355 , 0.0000792002 , 54794.08 , 54775.81530667 , error , minNumber , 0.0001|adausdt , 265895528661476 , 3.3928454747 , 1.301 , 1.30056634 , error , amountScale , 4|xrpusdt , 265895562871075 , 3.2312123456 , 1.36045 , 1.35999652 , error , amountScale , 2|kncusdt , 265898138608810 , 1.4467143782 , 3.0286 , 3.02759047 , error , amountScale , 2|eosusdt , 265898138609225 , 0.7339158085 , 5.9077 , 5.90573077 , error , amountScale , 4|avaxusdt , 265895672316162 , 0.1587895337 , 27.473 , 27.46384234 , error , amountScale , 4|mkrusdt , 265895511822999 , 0.0010051030 , 4379.66 , 4378.20011334 , error , amountScale , 6|1inchusdt , 265895554321367 , 0.8950986692 , 4.896705 , 4.89507277 , error , amountScale , 4|bchusdt , 265895571525228 , 0.0049537410 , 883.79 , 883.49540334 , error , amountScale , 4|dotusdt , 265895571427787 , 0.1302373386 , 33.6546 , 33.64338180 , error , amountScale , 4|ksmusdt , 265895554224163 , 0.0112193289 , 397.2695 , 397.13707684 , error , amountScale , 3|omgusdt , 265895537187233 , 0.5971992670 , 7.3931 , 7.39063564 , error , amountScale , 4|uniusdt , 265895503339102 , 0.1036638524 , 42.2492 , 42.23511694 , error , amountScale , 4|atomusdt , 265895562910662 , 0.1917993009 , 22.6669 , 22.65934437 , error , amountScale , 3|trxusdt , 265895562911326 , 35.9128189331 , 0.121937 , 0.12189636 , error , amountScale , 2|solusdt , 265895571496737 , 0.0975162189 , 45.9522 , 45.93688260 , error , amountScale , 2|crvusdt , 265895537190153 , 1.4652294302 , 2.9839 , 2.98290537 , error , amountScale , 4|xlmusdt , 265895562912991 , 8.9002691840 , 0.492613 , 0.49244880 , error , amountScale , 4|compusdt , 265895562815067 , 0.0067699479 , 650.96 , 650.74301334 , error , amountScale , 6|enjusdt , 265895520175548 , 1.6983562702 , 2.6827 , 2.68180577 , error , amountScale , 4';
                // 计算最小总价
                $minTotalList = 'sushiusdt , 265895369725468 , 0.2397995103 , 14.0458 , 14.04111807 , error , minTotal , 5|linkusdt , 265895545771070 , 0.0927467057 , 36.0632 , 36.05117894 , error , minTotal , 5|filusdt , 265895520310546 , 0.0221686738 , 150.038 , 149.98798734 , error , minTotal , 5|nearusdt , 265895554521634 , 0.6736597680 , 4.9827 , 4.98103910 , error , minTotal , 5|ethusdt , 265895520311719 , 0.0012416549 , 2710.56 , 2709.65648000 , error , minTotal , 5|aaveusdt , 265895545837974 , 0.0070707358 , 477.0531 , 476.89408230 , error , minTotal , 5|htusdt , 265895563076630 , 0.1817423592 , 18.3182 , 18.31209394 , error , minTotal , 5|ltcusdt , 265895494918289 , 0.0130847493 , 253.9 , 253.81536667 , error , minTotal , 5|zrxusdt , 265895503331945 , 1.9583603147 , 1.6771 , 1.67654097 , error , minTotal , 5|btcusdt , 265895562936355 , 0.0000607201 , 54599 , 54580.80033334 , error , minNumber , 0.0001|adausdt , 265895528661476 , 2.6011815306 , 1.292706 , 1.29227510 , error , minTotal , 5|xrpusdt , 265895562871075 , 2.4772627983 , 1.3416 , 1.34115280 , error , minTotal , 5|kncusdt , 265898138608810 , 1.1091476900 , 3.029 , 3.02799034 , error , minTotal , 5|eosusdt , 265898138609225 , 0.5626687865 , 5.8612 , 5.85924627 , error , minTotal , 5|avaxusdt , 265895672316162 , 0.1217386425 , 27.3413 , 27.33218624 , error , minTotal , 5|mkrusdt , 265895511822999 , 0.0007705790 , 4409.69 , 4408.22010334 , error , minTotal , 5|1inchusdt , 265895554321367 , 0.6862423131 , 5.075737 , 5.07404509 , error , minTotal , 5|bchusdt , 265895571525228 , 0.0037978681 , 878.17 , 877.87727667 , error , minTotal , 5|dotusdt , 265895571427787 , 0.0998486262 , 33.7423 , 33.73105257 , error , minTotal , 5|ksmusdt , 265895554224163 , 0.0086014855 , 402.2439 , 402.10981870 , error , minNumber , 0.01|omgusdt , 265895537187233 , 0.4578527714 , 7.3441 , 7.34165197 , error , minTotal , 5|uniusdt , 265895503339102 , 0.0794756201 , 42.1395 , 42.12545350 , error , minTotal , 5|atomusdt , 265895562910662 , 0.1470461306 , 22.4827 , 22.47520577 , error , minTotal , 5|trxusdt , 265895562911326 , 27.5331611821 , 0.121014 , 0.12097367 , error , minTotal , 5|solusdt , 265895571496737 , 0.0747624344 , 45.8063 , 45.79103124 , error , minTotal , 5|crvusdt , 265895537190153 , 1.1233425632 , 2.9944 , 2.99340187 , error , minTotal , 5|xlmusdt , 265895562912991 , 6.8235397078 , 0.491503 , 0.49133917 , error , minTotal , 5|compusdt , 265895562815067 , 0.0051902934 , 647.9 , 647.68403334 , error , minTotal , 5|enjusdt , 265895520175548 , 1.3020731405 , 2.6479 , 2.64701737 , error , minTotal , 5';

                $sellList = 'sushiusdt , 265895369725468 , 0.7193985309276492 , 13.8972 , 13.89256760 , ok , ok , 265899833194110|linkusdt , 265895545771070 , 0.2782401173180775 , 35.7553 , 35.74338157 , ok , ok , 265897156030986|filusdt , 265895520310546 , 0.0665060215271595 , 149.4827 , 149.43287244 , ok , ok , 265897198856374|nearusdt , 265895554521634 , 2.0209793041999108 , 4.9907 , 4.98903644 , ok , ok , 265897139094210|ethusdt , 265895520311719 , 0.0037249647285403 , 2684.14 , 2683.24528667 , ok , ok , 265897198335580|aaveusdt , 265895545837974 , 0.0212122075191536 , 473.9456 , 473.78761814 , ok , ok , 265897173040652|htusdt , 265895563076630 , 0.5452270777904645 , 18.2165 , 18.21042784 , ok , ok , 265897190243890|ltcusdt , 265895494918289 , 0.0392542479546884 , 252.36 , 252.27588000 , ok , ok , 265897164557010|zrxusdt , 265895503331945 , 5.8750809442514864 , 1.6703 , 1.66974324 , ok , ok , 265897198863495|btcusdt , 265895562936355 , 0.0001821605001930 , 54345.69 , 54327.57477000 , ok , ok , 265897215676014|adausdt , 265895528661476 , 7.8035445920184908 , 1.281968 , 1.28154068 , ok , ok , 265897215711749|xrpusdt , 265895562871075 , 7.4317883950911473 , 1.33648 , 1.33603451 , ok , ok , 265897198575197|kncusdt , 265898138608810 , 3.3274430700496782 , 2.9824 , 2.98140587 , ok , ok , 265897207357015|eosusdt , 265898138609225 , 1.6880063596231584 , 5.8263 , 5.82435790 , ok , ok , 265899849956961|avaxusdt , 265895672316162 , 0.3652159275130551 , 26.9498 , 26.94081674 , ok , ok , 265897164341452|mkrusdt , 265895511822999 , 0.0023117370457019 , 4330.45 , 4329.00651667 , ok , ok , 265897198713464|1inchusdt , 265895554321367 , 2.0587269393702853 , 5.32651 , 5.32473450 , ok , ok , 265897181316751|bchusdt , 265895571525228 , 0.0113936045117760 , 873.19 , 872.89893667 , ok , ok , 265899849963388|dotusdt , 265895571427787 , 0.2995458788429965 , 33.2799 , 33.26880670 , ok , ok , 265897198063056|ksmusdt , 265895554224163 , 0.0258044565175515 , 395.8176 , 395.68566080 , ok , ok , 265897164348709|omgusdt , 265895537187233 , 1.3735583142943653 , 7.2528 , 7.25038240 , ok , ok , 265897172868504|uniusdt , 265895503339102 , 0.2384268605298427 , 41.446 , 41.43218467 , ok , ok , 265897223823743|atomusdt , 265895562910662 , 0.4411383920719255 , 22.2909 , 22.28346970 , ok , ok , 265897215730995|trxusdt , 265895562911326 , 82.5994835463153015 , 0.119748 , 0.11970809 , ok , ok , 265899816358676|solusdt , 265895571496737 , 0.2242873034957805 , 45.647 , 45.63178434 , ok , ok , 265897155872739|crvusdt , 265895537190153 , 3.3700276896062673 , 2.9296 , 2.92862347 , ok , ok , 265897172879419|xlmusdt , 265895562912991 , 20.4706191234144499 , 0.487648 , 0.48748546 , ok , ok , 265897181334844|compusdt , 265895562815067 , 0.0155708802696040 , 642.97 , 642.75567667 , ok , ok , 265897333271787|enjusdt , 265895520175548 , 3.9062194215037770 , 2.64 , 2.63912000 , ok , ok , 265897266137386';

                $countValue = [];
                $explodeFunc = function($list){
                    $tmp = array_map(function($value){
                        return array_map(function($value){
                            return trim($value,' ');
                        },explode(',',$value));
                    },explode('|',$list));
                    $result = [];
                    foreach($tmp as $value) {
                        $result[$value[0]] = [
                            'num'   => $value[2],
                            'price' => $value[3],
                            'sell'  => $value[4],
                            $value[6] => $value[7],
                        ];
                    }
                    return $result;
                };
                $countList = [];
                $countList = $priceScaleList = $explodeFunc($priceScaleList);
                $minNumberList = $explodeFunc($minNumberList);
                $amountScaleList = $explodeFunc($amountScaleList);
                $minTotalList = $explodeFunc($minTotalList);
                foreach($countList as $key=>$value) {
                    $countList[$key] = array_merge($value,$minNumberList[$key]);
                }
                foreach($countList as $key=>$value) {
                    $countList[$key] = array_merge($value,$amountScaleList[$key]);
                }
                foreach($countList as $key=>$value) {
                    $countList[$key] = array_merge($value,$minTotalList[$key]);
                }
                foreach($countList as $key=>$value) {
                    if(!array_key_exists('priceScale',$value) || !array_key_exists('minNumber',$value) || !array_key_exists('amountScale',$value)) {
                        echo $key,'<br />';
                    }
                    if(!array_key_exists('minTotal',$value)) {
                        $countList[$key]['minTotal'] = 5;
                    }
                }

                echo '<pre>';
                foreach($countList as $key=>$value) {
                    Db::table('b_coin')->where([
                        'code'  => $key
                    ])->update([
                        'sell_price_scale'  => $value['priceScale'],
                        'sell_number_scale'  => $value['amountScale'],
                        'sell_number_min'  => $value['minNumber'],
                        'sell_total_min'  => $value['minTotal'],
                    ]);
                }
                print_r($countList);
                exit;


                $orderIds = 'sushiusdt,265895369725468|linkusdt,265895545771070|filusdt,265895520310546|nearusdt,265895554521634|ethusdt,265895520311719|aaveusdt,265895545837974|htusdt,265895563076630|ltcusdt,265895494918289|zrxusdt,265895503331945|btcusdt,265895562936355|adausdt,265895528661476|xrpusdt,265895562871075|kncusdt,265898138608810|eosusdt,265898138609225|avaxusdt,265895672316162|mkrusdt,265895511822999|1inchusdt,265895554321367|bchusdt,265895571525228|dotusdt,265895571427787|ksmusdt,265895554224163|omgusdt,265895537187233|uniusdt,265895503339102|atomusdt,265895562910662|trxusdt,265895562911326|solusdt,265895571496737|crvusdt,265895537190153|xlmusdt,265895562912991|compusdt,265895562815067|enjusdt,265895520175548';
                $orderIds = array_map(function($value){
                    return explode(',',$value);
                },explode('|',$orderIds));

                // 获取错误信息
                $getErrorMsgFunc = function ($errMsg) {
                    $type = 'unknown';
                    $mess = trim($errMsg);

                    $result = preg_replace_callback_array([
                        '/^order price precision error, scale: `([0-9]+)`$/'  => function($matches){
                            return 'priceScale' . '|' . $matches[1];
                        },
                        '/^Number of orders can not be less than `([0-9]+(\.[0-9]+)?)`$/' => function($matches){
                            return 'minNumber' . '|' . $matches[1];
                        },
                        '/^order amount precision error, scale: `([0-9]+)`$/' => function($matches){
                            return 'amountScale' . '|' . $matches[1];
                        },
                        '/^Order total cannot be lower than: `([0-9]+)`$/' => function($matches){
                            return 'minTotal' . '|' . $matches[1];
                        },
                    ],$mess);
                    $result = explode('|',$result);
                    if(count($result) == 2) {
                        list($type,$mess) = $result;
                    }
                    return [$type,$mess];
                };

              /*  $errorList = [];
                foreach($orderIds as list($symbol,$orderId)) {
                    try {
                        $result = $huobi->get_order($orderId);
                        $num = bcsub($this->convert_scientific_number_to_normal($result['data']['field-amount']),$this->convert_scientific_number_to_normal($result['data']['field-fees']),16); // 获取数量
                        $price = $huobi->get_history_trade($symbol,1)['data'][0]['data'][0]['price'];   // 获取最新单价
                        $newPrice = bcsub($price,bcdiv($price,3000,8),8);// 获取卖出单价
                        // 卖出操作
                        $result = $huobi->place_order($accountId,bcsub($num,0,$countList[$symbol]['amountScale']),bcsub($newPrice,0,$countList[$symbol]['priceScale']),$symbol,'sell-limit');
                        $echoArr = [$symbol,$orderId,$num,$price,$newPrice,$result['status']];
                        if($echoArr[5] == 'error') {
                            $echoArr = array_merge($echoArr,$getErrorMsgFunc($result['err-msg']));
                        } else {
                            $echoArr[] = 'ok';
                            $echoArr[] = $result['data'];
                        }

                        echo implode(' , ',$echoArr),'|';


                    }catch (\Exception $e) {
                        $errorList[] = [
                            $symbol,$orderId,$e->getMessage(),
                        ];
                    }
                }
                echo '<pre>';
                print_r($errorList);
                exit;
                echo '<pre>';
                print_r($orderIds);*/
                echo '<br /><br />>';
                print_r($huobi->get_balance()['data']['list'][724]);
                exit;
           //     print_r($huobi->get_history_trade('bchusdt'));exit;

        //          $result = $huobi->place_order($accountId,10,0,$symbol,'buy-market'); // 买入

              /*  $result = $huobi->get_order(265184802321667);  $num = bcsub($result['data']['field-amount'],$result['data']['field-fees'],16);//查询订单
                $price = $huobi->get_history_trade($symbol,1)['data'][0]['data'][0]['price'];  $newPrice = bcsub($price,bcdiv($price,3000,8),8);// 获取当前
                $num = 0.1;

                $result = $huobi->place_order($accountId,bcsub($num,0,3),bcsub($newPrice,0,3),$symbol,'sell-limit');*/

                echo '<pre>';
              /*  print_r($result);*/
                print_r($huobi->get_balance()['data']['list'][722]);
                exit;

            case 'log': // 日志统计计算
                $this->countLog();
                exit;
            case 'call_api':
                print_r($this->getCallApi());
                exit;
            case 'request':
                echo Request::domain(),"\n";
                print_r(request());
                exit;
        }





        echo "\n计算规则：\n";
        $max = 400;
        $result = [];
        for($i=300;$i<$max;++$i) {
            if($resultOne = HistoryTrade::tcpTableQuery(RuleCalculation::TABLE_MONITOR_RULE_LIST . ' ' . $i,$port)) {
                if(is_array($resultOne['result'])) {
                    if(strlen($resultOne['result']['last_fetch_time']) > 10) {
                        $resultOne['result']['last_fetch_time'] = ceil($resultOne['result']['last_run_time']);
                        $result[$i . '_' . $resultOne['result']['code']] = '[1]';
                    } else {
                        $result[$i . '_' . $resultOne['result']['code']] = '[0]';
                    }

                    $result[$i . '_' . $resultOne['result']['code']] .= date('Y-m-d H:i:s',$resultOne['result']['last_fetch_time']);
                }

            }
        }
        arsort($result);
        print_r($result);
        print_r(HistoryTrade::tcpTableQuery(RuleCalculation::TABLE_MONITOR_RULE_LIST . ' ' . $getFunc('id'),$port));
        /*$getTimeFunc = function($time){
            $timeArr = explode('.',$time);
            if(count($timeArr) != 2) {
                $timeArr = [substr($time,0,-3),substr($time,-3)];
            }
            return date('Y-m-d H:i:s ',$timeArr[0]) . $timeArr[1];
        };
        $result['time'] = $getTimeFunc($result['time']);
        foreach($result['result'] as &$value) {
            $value['last_fetch_time'] = $getTimeFunc($value['last_fetch_time']);
        }*/


        exit;


//连接到服务器
        if (!$client->connect('127.0.0.1', 9501)) die("connect failed.");


        $content = HistoryTrade::TABLE_SELECT_RUN;
        $body = pack('N', strlen($content)) . $content;

//向服务器发送数据
   !$client->send($body);


//从服务器接收数据
        $data = $client->recv();



//解包 去掉包头数据
        $body = unpack('N',$data);
        $content = substr($data,4,reset($body)); // 这里的 4 的计算公式  N 为32字节序 1字节等于8bit 32 / 8 = 4
        var_dump($content);

//关闭连接
        $client->close();


        $readSize = 2;
        $st= HistoryTrade::TABLE_SELECT_RUN;
        $length = strlen($st);
//创建tcp套接字
        $socket = socket_create(AF_INET,SOCK_STREAM,SOL_TCP);
//连接tcp
        socket_connect($socket, '127.0.0.1',9501);
//向打开的套集字写入数据（发送数据）
        $s = socket_write($socket, $st, $length);
//从套接字中获取服务器发送来的数据
        $msg = '';
        $i = 0;
        while(true) {
            $tmp = socket_read($socket,$readSize);
            $msg .= $tmp;
            if(strlen($tmp) != $readSize || $i++ == 1000) {
                break;
            }
        }
        //关闭连接
        socket_close($socket);
        $msg = json_decode($msg,true);
        echo '<pre>';
        print_r($msg);
        exit;

  /*      $ruleDetails['min_price'] = 0.500355;
        $ruleDetails['cover_callback'] = 0.3;
        $ruleDetails['cover_price']  = bcadd($ruleDetails['min_price'],bcmul($ruleDetails['min_price'],bcdiv($ruleDetails['cover_callback'],100,8),$this->scale),$this->scale);

        echo '<pre>';
        print_r($ruleDetails);
exit;*/
        $req = new Huobi(23150905,'9bc53367-mn8ikls4qg-58abf940-2a719','7f54d9ca-4064fa0f-4f1ba2f7-72eac');
      /*  echo '<pre>';
        print_r($req->get_account_balance());exit;*/
        echo '<pre>';
        print_r($result = $req->get_history_trade('xlmusdt'));
        exit;
        var_dump($result = $req->place_order(23150905,25.08715832,0,'xlmusdt','sell-limit'));
        echo '<pre>';
        print_r($result);exit;
        echo '<pre>';
        print_r($req->get_order_orders('xlmusdt'));exit;
        echo '<pre>';
        print_r($req->get_account_balance());exit;
        var_dump($result = $req->place_order(23150905,2,0,'ltcusdt','buy-market','A000000000100000000380000010001'));
        echo '<pre>';
        print_r($result);exit;
        echo '<pre>';
        print_r($req->get_order('255755738562719'));exit;
        echo '<pre>';
        print_r($req->get_account_balance());exit;
        var_dump($result = $req->place_order(23150905,5,0,'ltcusdt','buy-market','A000000000100000000380000010001'));
        echo '<pre>';
        print_r($result);
        exit;
        echo '<pre>';
        print_r($req->get_common_timestamp());exit;
        $sysTime = ($req->get_common_timestamp()->data);
        $time = floor($sysTime/1000);
        $times = $sysTime % 1000;
        echo '货币服务器时间：' . date('Y-m-d H:i:s',$time) . ' ' . $times . '<br />';
        echo '本地系统时间：' . date('Y-m-d H:i:s') .'<br />';
        // 写入redis
        $redis = Cache::store('redis');
        $list = $redis->hkeys('btcusdt');
        echo '该货币总共缓存数据数：' . count($list) . '<br />';

        rsort($list);
        $list = array_slice($list,0,20);
        $result = [];
        foreach($list as $key) {
            $key = explode('_',$key);
            $key = $key[0];
            $time = floor($key/1000);
            $times = $key % 1000;
            $key = date('Y-m-d H:i:s',$time) . ' ' . $times;
            if(!array_key_exists($key,$result)) {
                $result[$key] = 0;
            }

            ++$result[$key];
        }
        echo '<pre>';
        print_r($result);exit;

    }

}